package com.whccb.apps.office.document.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.servicetask.ServiceDelegate;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.Logger;
import com.whccb.apps.office.document.util.CMSUtil;
import com.whccb.apps.office.document.util.DictUtil;

import net.sf.json.JSONArray;

public class CreateUrlCmsServiceAtTxwj extends ServiceDelegate {

	private static final Logger logger = LogAPI.getLogger(CreateUrlCmsServiceAtTxwj.class);
	
	public String getDescription() {
		return "规章制度/体系文件流程结束后，自动发布CMS内容，采用URL方式。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public boolean execute(ProcessExecutionContext pec) throws Exception {
		logger.info("--------规章制度/体系文件，我进入发布CMS服务------------");
		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(pec.getProcessInstance().getId());
		
		if (paramMap != null && !paramMap.isEmpty()) {
			
			String boName = paramMap.get("BONAME") != null ? paramMap.get("BONAME").toString() : "";
			String cmsModelid = paramMap.get("REFCMSMODELID") != null ? paramMap.get("REFCMSMODELID").toString() : "";
			String formDefId = paramMap.get("CMSFORMDEFID") != null ? paramMap.get("CMSFORMDEFID").toString() : "";
			
			logger.info("规章制度/体系文件,boName="+boName+",cmsModelid="+cmsModelid+",formDefId="+formDefId);
			
			BO bo = SDK.getBOAPI().getByProcess(boName, pec.getProcessInstance().getId());
			
			if (bo != null) {
				/**
				 * PDF路径
				 */
				String zwPdfUrl = bo.getString("PDFURL");
				
				logger.info("规章制度/体系文件，zwPdfUrl="+zwPdfUrl);
				
				if (StringUtils.isNotBlank(zwPdfUrl)) {
					
					StringBuilder title = new StringBuilder();
					
					/**
					 *  01:纲要政策|02:基本管理制度|03:具体管理制度|04:体系文件
					 */
					String reg_level_dict = bo.getString("REG_LEVEL_DICT");
					
					if (StringUtils.isNotBlank(reg_level_dict)) {
						String fileTypeName = DictUtil.getDictValue("WHBK.OD.GRC.FILE.TYPE", reg_level_dict);
						title.append("<").append(fileTypeName).append(">");
					}

					if (StringUtils.isNotBlank(bo.getString("FILE_NAME"))) {
						title = title.append(bo.getString("FILE_NAME"));
					}
					
					/**
					 * 制度名称
					 */
					String titleName  = SDK.getRuleAPI().executeAtScript("@substring(" + title.toString() + ",0,100)");
					
					logger.info("规章制度/体系文件，制度名称为：titleName="+titleName);
					
					if (StringUtils.isNotBlank(cmsModelid)) {
						
						String taskInstId = "";
						List<HistoryTaskInstance> hisTaskList = SDK.getHistoryTaskQueryAPI()
								.processInstId(pec.getProcessInstance().getId()).activityType("userTask")
								.orderByEndTime().desc().list();
						
						if (CollectionUtils.isNotEmpty(hisTaskList)) {
							taskInstId = hisTaskList.get(0).getId();
						}
						
						logger.info("规章制度/体系文件，任务节点ID为：taskInstId="+taskInstId);
						
						String createUserId = bo.getString("REG_USER_CODE");
						
						JSONArray attachmentList = CMSUtil.getAttach(bo.getId(), "ZW", "ACCESSORY_ATTFILE");
						// 调用发布cms数据的方法
						String cmsid = CMSUtil.createUrlCmsData(pec.getUserContext(), cmsModelid,
								pec.getProcessInstance().getId(), taskInstId, formDefId, titleName, attachmentList, null, boName,
								"PDFFILE", "ACCESSORY_ATTFILE", createUserId);
						
						String updateSql = " UPDATE " + boName + " SET CMSMODELID =:CMSMODELID,REFCMSID=:REFCMSID WHERE ID = :ID";
						Map<String, Object> updateMap = new HashMap<String, Object>();
						updateMap.put("CMSMODELID", cmsModelid);
						updateMap.put("REFCMSID", cmsid);
						updateMap.put("ID", bo.getId());
						DBSql.update(updateSql, updateMap);
					}
				}
			}
		}
		logger.info("--------体系文件，发布CMS服务完成------------");
		return true;
	}

}
